<template>
  <SearchBar @sendData="getSearchData" :searchList="searchList"></SearchBar>


  <a-button type="primary" @click="showModal('add')" v-auth="'user:add'">添加用户</a-button>
  <!-- <a-button type="primary" @click="showModal('add')" v-if="userModel.permissions.includes('user:add')">添加用户</a-button> -->

  <a-table :columns="columns" :data-source="userList" row-key="userId" 
  :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }">
    <template #headerCell="{ column }">
      <!-- column ：标头当前的数据 -->
      <template v-if="column.dataIndex === 'username'">
        <span :style="{color:'red'}">
          用户名
        </span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <!-- column ： 标头定义部分
      record：当前某一条数据 -->
      <template v-if="column.key=='ssex'">
        <span v-if="record.ssex==2">男</span>   
         <span v-if="record.ssex==1">女</span>
         <span v-if="record.ssex==0">保密</span>
      </template>
      <template v-if="column.dataIndex =='status'" >
        <span v-if="record.status==1">有效</span>   
        <span v-else>无效</span>
      </template>
      <template v-if="column.key === 'action'">
        <a-button type="primary" @click="showModal('edit',record)">编辑</a-button>
        <a-button >删除</a-button>
      </template>
    </template>
  </a-table>

  <a-drawer
        v-model:open="modalObj.open"
        :title="modalObj.title"
        placement="right"  width="600px" :destroyOnClose="true"
      >
      <FormPublic  :formList="formList" :kind="modalObj.kind"  :actions="{
        add:{
          url:'/user',
          method:'post'
        },
        edit:{
          url:'user',
          method:'put'
        }
        }" 
      rowKey="userId"
      :currentData="currentData"
      
      ></FormPublic>
      <!-- <FormPublic 
        :formList="formList" 
        :formApi="testFormApi[modalObj.kind as IComType]" 
        :rowCol = "currentData"
        :kind="modalObj.kind"></FormPublic> -->

       <!-- 静态 -->
        <!-- <FormUser></FormUser> -->
      </a-drawer>

</template>
<script lang="ts" setup>
import {ref,reactive, onMounted,watchEffect,watch} from 'vue'
import axiosEl from '@/utils/axios';
import SearchBar from '@/components/search/SearchBar.vue'
import FormUser from '@/components/form/FormUser.vue'

import FormPublic from '@/components/form/FormPublic.vue'
import type {ISearchOption} from '@/interface/user'
import type {IFormProps} from '@/interface/form'

import {useUserInfo} from '@/stores/userinfo'

const userModel = useUserInfo();

type Ikind = 'add' | 'edit';
interface IModalProps {
    open: boolean;
    title: string;
    kind: Ikind;
}
  // form表单的option
  const formList:IFormProps[] = [
  {
    type:'text',
    label:'用户名',
    name:'username',
    rules:[{
      required:true
    }],
  },
  {
    type:'password',
    label:'密码',
    name:'password',
    initval:'1234qwer',
    readOnly:true,
    show:false,   
    rules:[{
      required:true
    }],
  },
  {
    type:'select',
    label:'角色',
    name:'roleId',
    options:[],
    mode:'multiple',  //为了可以支持多选
    rules:[{
      required:true
    }],
    fieldNames:{
      label:'roleName',
      value:'roleId'
    },
    optionApi:{
      url:'/role',
      method:'get',
      data:{
        pageSize:999
      }
    }
  },
  {
    type:'radio',
    label:'状态',
    name:'status',
    initval:'1',  // 默认值
    rules:[{
      required:true
    }],
    options:[{ value: '1', label: '有效' },{ value: '0', label: '无效' }]
  },
  {
    type:'radio',
    label:'性别',
    name:'ssex',
    initval:'0',  // 默认值
    rules:[{
      required:true
    }],
    options:[{ value: '0', label: '男' },{ value: '1', label: '女' },{ value: '2', label: '保密' }]
  },
  {
    type:'text',
    label:'邮箱',
    name:'email'
  },
  {
    type:'text',
    label:'手机号',
    name:'mobile',
    show:false,  
    rules:[{
      required:true
    },
    {
      pattern:/^[1][3,4,5,7,8][0-9]{9}$/,
      error:'你的邮箱格式不对'
    }]
  },
  {
    type:'treeselect',
    label:'部门',
    name:'deptId',
    options:[],
    rules:[{
      required:true
    }],
    // fieldNames:{
    //   label:'title',
    //   value:'value'
    // },
    optionApi:{
      url:'/dept',
      method:'get'
    }
  },
]

const searchList:IFormProps[] = [{
  label:'用户名',
  name:'username',
  type:'text'
},{
  label:'部门',
  name:'deptId',
  type:'treeselect',
  optionApi:{
    url:'/dept',
    method:'get'
  }
},{
  label:'开始日期',
  name:'createTimeFrom',
  type:'datepicker'
},{
  label:'结束日期',
  name:'createTimeTo',
  type:'datepicker'
}]
const selectedKeys = ref<string[]>([])
  // 模态框的数据   open  , title
  const modalObj = reactive<IModalProps>({
    open:false,
    title:'新增',
    kind:'add'
  })
// 当前修改的数据
const currentData = ref<any>({})
  // 显示模态框
const showModal = (kind:Ikind,data?:any)=>{
  modalObj.open = true;
  modalObj.kind = kind;
  modalObj.title = kind == 'add' ? '新增' :'编辑';

    formList.forEach((option)=>{
        if(['mobile','password'].includes(option.name)) {

           if(kind=='add') {
            option.show = true
           } else {
            option.show = false
           }
           
        }
    })
  
  currentData.value = data;
}
const onSelectChange = (rows: string[]) => {
  console.log('selectedRowKeys changed: ', rows);
  selectedKeys.value = rows;
};

const searchOption = ref<ISearchOption>({})
// 用户列表的数据源
const  userList = ref([])
const columns = [
    {
        title: '用户名',
        dataIndex: 'username',
        sorter: (a:any, b:any) => a.username - b.username,
    },
    {
        title: '性别',
        dataIndex: 'ssex',
        key:'ssex',
        filters: [
            {
              text: '男',
              value: '1',
            },
            {
              text: '女',
              value: '0',
            }
          ]
    },
    {
        title: '邮箱',
        dataIndex: 'email',
    },
    {
        title: '角色',
        dataIndex: 'roleName',
    },
    {
        title: '部门',
        dataIndex: 'deptName',
    },
    {
        title: '电话',
        dataIndex: 'mobile',
    },
    {
        title: '状态',
        dataIndex: 'status'
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        defaultSortOrder: 'descend',
        sorter: (a:any, b:any) => a.createTime - b.createTime,
    },
    {
        title: '操作',
        key: 'action',
        width:160,
    },

  ];

const getUserList = ()=>{
  axiosEl({
    method:'get',
    url:'/user',
    params: searchOption.value
  }).then((res)=>{

    res.rows.forEach((item:any)=>{
   
   if(item.roleId) {
     item.roleId = item.roleId.split(',').map((str:string)=>{
       return Number(str)
     });   
     console.log(item.roleId,'item.roleId');
     
     // item.roleId 是一个数组， 但是每项都需要是number类型的
   }
})

    userList.value = res.rows;
   })
}

//   获取到搜索的额数据
const getSearchData = (data:any)=>{
  console.log('获取到子组件的值',data);
  searchOption.value  = {...searchOption.value , ...data};
  getUserList();   //  不需要等模板渲染， 可以直接调接口
}
onMounted(()=>{
  getUserList();
})

</script>

